package com.ld.shieldsb.qrcode.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.qrcode.service.QRCodeService;
import com.ld.shieldsb.qrcode.writer.QRCodeNoPaddingWriter;

public class QRCodeCommonService extends QRCodeService {

    @Override
    public BufferedImage createImage(String content, String logoImagePath, int width, int logowidth) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new QRCodeNoPaddingWriter().encode(content, BarcodeFormat.QR_CODE, width, width, hints);
        BufferedImage image = toBufferedImage(bitMatrix, width, width); // 如果图片尺寸不对在此方法调整
        if (logoImagePath == null || "".equals(logoImagePath)) {
            return image;
        }
        if (StringUtils.isNotEmpty(logoImagePath) && logowidth > 0) {
            // 插入中间图片
            overlapImage(image, logoImagePath, logowidth);
        }
        return image;
    }

    @Override
    public void encode(String content, String logoImagePath, int width, int logowidth, String destImagePath) throws Exception {
        BufferedImage image = createImage(content, logoImagePath, width, logowidth);
        mkdirs(destImagePath);
        // String file = new Random().nextInt(99999999)+".jpg";
        // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        ImageIO.write(image, FORMAT_NAME, new File(destImagePath));

    }

    @Override
    public BufferedImage encode(String content, String logoImagePath, int width, int logowidth) throws Exception {
        BufferedImage image = createImage(content, logoImagePath, width, logowidth);
        return image;
    }

}
